<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\RoleRequest;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $role = Role::where('name','!=','master')->get();
//        dd($role);
        return view('admin::role.index',compact('role'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('admin::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(RoleRequest $request)
    {
        $post = $request->all();
        Role::create($post);
        session()->flash('success','添加成功');
        return redirect()->route('role.index');
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(RoleRequest $request,$id)
    {
        $role = Role::find($id);
        $role->title = $request->input('title');
        $role->name = $request->input('name');
        $role->save();
        session()->flash('success','角色编辑成功');
        return redirect()->route('role.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        $role  = Role::find($id);
        $role->delete();
        session()->flash('success','角色删除成功');
        return back();
    }
    public function showPermission($roleid){
        $role = Role::find($roleid);
//        dd($roleid);
        $permission = \HDModule::getPermissionByGuard('admin');
//        dd($permission);
        return view('admin::role.permission',compact('permission','role'));
    }
    //处理分配权限方法
    public function permission(Request $request,$roleid){
        if(empty($request->input('name'))){
            session()->flash('danger','未选择任何角色');
            return redirect()->route('role.index');
        }
        $role = Role::find($roleid);
        //使用手册中的同步方法为角色添加权限
        $role->syncPermissions($request->input('name'));
        session()->flash('success','添加成功');
        return redirect()->route('role.index');
    }
}
